import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:gim_plugin/gim_plugin.dart';
import 'package:gim_plugin_example/pages/overlay_liver/artc/liver_1v1_store.dart';
import 'package:gim_plugin_example/pages/overlay_liver/artc/views/audio_room.dart';
import 'package:gim_plugin_example/pages/overlay_liver/artc/views/holding.dart';
import 'package:gim_plugin_example/pages/overlay_liver/artc/views/video_room.dart';

import 'package:gim_plugin_example/sdk/artc_sdk.dart';
import 'package:gim_plugin_example/sdk/gim_sdk.dart';
import 'package:gim_plugin_example/utils/data_utils.dart';
import 'package:gim_plugin_example/utils/toast_utils.dart';
import 'package:provider/provider.dart';

import '../../../global.dart';
import 'liver_1v1_room_overlay.dart';

class Liver1V1 extends StatelessWidget {
  final bool videoCall;
  final String channelName;
  final bool master;
  final int signalingId;
  final String remoteUid;
  final String remoteNickname;
  final String remoteAvatar;

  Liver1V1(
      {Key? key,
      required this.videoCall,
      required this.channelName,
      required this.master,
      required this.signalingId,
      required this.remoteUid,
      required this.remoteNickname,
      required this.remoteAvatar})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
            create: (_) => Liver1V1Store(
                videoCall: videoCall,
                channelName: channelName,
                master: master,
                signalingId: signalingId,
                remoteUid: remoteUid,
                remoteNickname: remoteNickname,
                remoteAvatar: remoteAvatar)),
      ],
      child: _Liver1V1(videoCall: videoCall),
    );
  }
}

class _Liver1V1 extends StatefulWidget {
  final bool videoCall;

  _Liver1V1({Key? key, required this.videoCall}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _Liver1V1State();
}

class _Liver1V1State extends State<_Liver1V1> {
  ArtcSdk artcSdk = ArtcSdk();

  @override
  void initState() {
    var store = context.read<Liver1V1Store>();
    store.artcSdk = artcSdk;
    artcSdk.initClient(context,
        videoCall: widget.videoCall,
        cb: store.cb!);
    gimSdk.gim.addSignalingFn(signalingCb);
    super.initState();
  }

  @override
  void dispose() {
    artcSdk.delChannel();
    gimSdk.gim.delSignalingFn(signalingCb);
    super.dispose();
  }

  void signalingCb(SignalingMsg msg) async {
    if (msg.event == EventTypes.SignalingCancel) {
      liver1v1roomOverlay.close();
      showToast('通话已取消');
    } else if (msg.event == EventTypes.SignalingAccept) {
      var store = context.read<Liver1V1Store>();
      if (store.master) {
        //进入房间
        var global = context.read<Global>();
        var uid = int.parse(global.uid!.split('_')[1]);
        var dto = await gimSdk.gim.getArtcToken(uid: uid, channelName: store.channelName);
        if (dto == null) return;
        store.artcSdk!.createChannel(uid: uid, rtcToken: dto.token!, channelId: store.channelName);
        store.updateEnterRoom();
      }
    } else if (msg.event == EventTypes.SignalingReject) {
      liver1v1roomOverlay.close();
      if (notBlack(msg.extData)) {
        var extData = json.decode(msg.extData);
        showToast(extData['msg']);
      } else {
        showToast('对方正忙');
      }
    } else if (msg.event == EventTypes.SignalingTimeout) {
      liver1v1roomOverlay.close();
      showToast('对方无应答');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Selector(
        builder: (BuildContext context, bool enterRoom, Widget? child) {
          return !enterRoom
              ? Holding()
              : widget.videoCall
                  ? VideoRoom()
                  : AudioRoom();
        },
        selector: (BuildContext context, Liver1V1Store store) => store.enterRoom);
  }
}
